/*
 * Copyright (C) 2007-2009 Alessandro Melandri
 * 
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package net.melandri.jtextfileparser.filters;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import net.melandri.jtextfileparser.beans.Row;
import net.melandri.jtextfileparser.dao.FileManager;

/**
 * Class for filtering a TextFile object. This is used to export TextFile content
 * 
 * @since 1.3.1
 * */
public class TextFileFilter extends OutputFileFilterImpl implements OutputFileFilter{
	
	private String separator = null;

	/**
	 * Contains the code to write data to the file system. This method is used when you invoke the <code>write</code> method in a TextFile object.
	 * 
	 * @param rows ArrayList of Row objects.
	 * @since 1.4
	 * */
	public void write(ArrayList rows){
		
		FileManager newFile = new FileManager(this.fileName, this.filePath);
		newFile.createFile();
		
		ArrayList filteredRows = getRowsSubset(rows);
		
		Iterator it = filteredRows.iterator();

		try {

			while (it.hasNext()) {

				Row row = (Row) it.next();

				String stringRow = "";
				String[] fields = row.getFields();

				for (int i = 0; i < fields.length; i++) {

					stringRow += fields[i];

					if (i != fields.length - 1)
						stringRow += this.separator;
				}

				newFile.writeLine(stringRow);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				newFile.closeWrite();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	/* -------------------- Getters and Setters -------------------- */
	

	public String getSeparator() {
		return separator;
	}

	public void setSeparator(String separator) {
		this.separator = separator;
	}

}
